﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace WindowsGame1
{
    class TileMapLayer
    {
        int[,] map;

        public TileMapLayer(int x, int y)
        {
            map = new int[y, x];
        }

        public int TileMapWidth
        {
            get { return map.GetLength(1); }
        }

        public int TileMapHeight
        {
            get { return map.GetLength(0); }
        }

        public void SetTile(int x, int y, int tileIndex)
        {
            map[y, x] = tileIndex;
        }

        public int GetTile(int x, int y)
        {
            return map[y, x];
        }

        private Point VectorToCell(Vector2 vector)
        {
            return new Point(
            (int)(vector.X / TileEngine.TileWidth),
            (int)(vector.Y / TileEngine.TileHeight));
        }

        public void Draw(SpriteBatch sBatch, Texture2D texture, Tileset tileset)
        {
            Point cameraPoint = VectorToCell(Game1.Camera.Position);
            Point viewPoint = VectorToCell(Game1.Camera.Position +
            TileEngine.ViewPortVector);
            Point min = new Point();
            Point max = new Point();
            min.X = cameraPoint.X;
            min.Y = cameraPoint.Y;
            max.X = (int)Math.Min(viewPoint.X, map.GetLength(1));
            max.Y = (int)Math.Min(viewPoint.Y, map.GetLength(0));
            Rectangle tileRectangle = new Rectangle(
            0,
            0,
            TileEngine.TileWidth,
            TileEngine.TileHeight);
            sBatch.Begin(SpriteBlendMode.AlphaBlend,
            SpriteSortMode.BackToFront,
            SaveStateMode.None,
            Game1.Camera.TransformMatrix);
            for (int x = min.X; x < max.X; x++)
            {
                for (int y = min.Y; y < max.Y; y++)
                {
                    if (map[y, x] != -1)
                    {
                        tileRectangle.X = x * TileEngine.TileWidth;
                        tileRectangle.Y = y * TileEngine.TileHeight;
                        sBatch.Draw(texture,
                        tileRectangle,
                        tileset.Tiles[map[y, x]],
                        Color.White);
                    }
                }
            }
            sBatch.End();
        }
    }
}
